package com.bnlr.lrparking.appui.publish;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.UpImgM;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.CompressPhotoUtils;
import com.bnlr.lrparking.util.DbTOPxUtils;
import com.bnlr.lrparking.util.MyGridView;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.PhotoPreviewActivity;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;
import com.zzti.fengyongge.imagepicker.util.CommonUtils;
import com.zzti.fengyongge.imagepicker.util.FileUtils;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.bnlr.lrparking.R.id.add_IB;

/**
 * 发布  编辑车位图片
 */
public class EditStallPhotoActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.gv_stall)
    MyGridView gvStall;
    @BindView(R.id.file_stall)
    MyGridView gvFile;
    private GridImgAdapter gridImgsAdapter;
    private GridFileAdapter gridFileAdapter;
    private int screen_widthOffset;
    private String upTag ="1";
    private List<String> imgArray = new ArrayList<>();
    private List<String> fileArray = new ArrayList<>();
    private String path = "";
    private String path2 = "";
    private List<PhotoModel> single_img_photos = new ArrayList<PhotoModel>();
    private List<PhotoModel> single_file_photos = new ArrayList<PhotoModel>();
    private boolean isUpdate = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_stall_photo);
        unbinder = ButterKnife.bind(this);
        Intent intent = getIntent();
        imgArray = (List<String>) intent.getSerializableExtra("imgList");
        fileArray = (List<String>) intent.getSerializableExtra("fileList");
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screen_widthOffset = (display.getWidth() - (3* DbTOPxUtils.dip2px(this, 2)))/3;
        gridImgsAdapter = new GridImgAdapter();
        gridFileAdapter = new GridFileAdapter();
        gvFile.setAdapter(gridFileAdapter);
        gvStall.setAdapter(gridImgsAdapter);


        for (int i = 0; i < imgArray.size(); i++) {
            PhotoModel photoModel = new PhotoModel();
            photoModel.setOriginalPath(imgArray.get(i));
            photoModel.setChecked(true);
            single_img_photos.add(photoModel);
        }
        for (int i = 0; i < fileArray.size(); i++) {
            PhotoModel photoModel = new PhotoModel();
            photoModel.setOriginalPath(fileArray.get(i));
            photoModel.setChecked(true);
            single_file_photos.add(photoModel);
        }

        if (imgArray.size() < 3) {
            imgArray.add(null);
        }
        if (fileArray.size() < 9) {
            fileArray.add(null);
        }
        gridImgsAdapter.notifyDataSetChanged();
        gridFileAdapter.notifyDataSetChanged();
    }
    @OnClick({R.id.tv_select_finish,R.id.iv_back})
    public void editStall (View view) {
        switch (view.getId()) {
            case R.id.tv_select_finish:
                /*if (imgArray.get(0) == null) {
                    ToastUtils.showShort("车位图片不能为空");
                    return;
                }
                if (fileArray.get(0) == null) {
                    ToastUtils.showShort("相关文件不能为空");
                    return;
                }*/
                Intent intent = new Intent();
                for (int i = 0; i < imgArray.size(); i++) {
                    if (null == imgArray.get(i)) {
                        imgArray.remove(i);
                    }
                }
                for (int i = 0; i < fileArray.size(); i++) {
                    if (null == fileArray.get(i)) {
                        fileArray.remove(i);
                    }
                }
                intent.putExtra("imgList", (Serializable) imgArray);
                intent.putExtra("fileList", (Serializable) fileArray);
                setResult(1006,intent);
                finish();
                break;
            case R.id.iv_back:
                exitEdit();
                break;
            default:
                break;
        }
    }

    private void exitEdit() {
        if (isUpdate) {
            CarCommon carCommon = new CarCommon();
            carCommon.CommonDialog(this,"退出后，本次操作将无法保存，是否退出","提示");
            carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                @Override
                public void setSure() {
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    class GridImgAdapter extends BaseAdapter implements ListAdapter {

        @Override
        public int getCount() {
            return imgArray.size();
        }
        @Override
        public Object getItem(int position) {
            return imgArray.get(position);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(EditStallPhotoActivity.this).inflate(R.layout.activity_addstory_img_item, null);
            ViewHolder holder;
            if(convertView!=null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(EditStallPhotoActivity.this).inflate(R.layout.activity_addstory_img_item,null);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.add_IB = (ImageView) convertView.findViewById(add_IB);
            holder.delete_IV = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (imgArray.get(position) == null) {
                holder.delete_IV.setVisibility(View.GONE);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        upTag = "1";
                        Intent intent = new Intent(EditStallPhotoActivity.this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 3 - (imgArray.size() - 1));
                        startActivityForResult(intent, 1000);

                    }
                });
            } else {
                Glide.with(EditStallPhotoActivity.this).load(imgArray.get(position)).into(holder.add_IB);
                holder.delete_IV.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;
                    @Override
                    public void onClick(View arg0) {
                        isUpdate = true;
                        is_addNull = true;
                        String img_url = imgArray.remove(position);
                        single_img_photos.remove(position);
                        for (int i = 0; i < imgArray.size(); i++) {
                            if (imgArray.get(i) == null) {
                                is_addNull = false;
                                break;
                            }
                        }
                        if (is_addNull) {
                            imgArray.add(null);
                        }
                        FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                });
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos",(Serializable)single_img_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave",false);
                        bundle.putBoolean("isNet",true);
                        CommonUtils.launchActivity(EditStallPhotoActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }
        class ViewHolder {
            ImageView add_IB;
            ImageView delete_IV;
        }

    }
    class GridFileAdapter extends BaseAdapter implements ListAdapter {

        @Override
        public int getCount() {
            return fileArray.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(EditStallPhotoActivity.this).inflate(R.layout.activity_addstory_img_item, null);
            GridFileAdapter.ViewHolder holder;
            if(convertView!=null){
                holder = new GridFileAdapter.ViewHolder();
                convertView = LayoutInflater.from(EditStallPhotoActivity.this).inflate(R.layout.activity_addstory_img_item,null);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.add = (ImageView) convertView.findViewById(add_IB);
            holder.delete = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (fileArray.get(position) == null) {
                holder.delete.setVisibility(View.GONE);
                holder.add.setImageResource(R.mipmap.addimg);
                holder.add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        upTag = "2";
                        Intent intent = new Intent(EditStallPhotoActivity.this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 9 - (fileArray.size() - 1));
                        startActivityForResult(intent, 1001);

                    }
                });
            } else {
                Glide.with(EditStallPhotoActivity.this).load(fileArray.get(position)).into(holder.add);

                holder.delete.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;
                    @Override
                    public void onClick(View arg0) {
                        isUpdate = true;
                        is_addNull = true;
                        String img_url = fileArray.remove(position);
                        single_file_photos.remove(position);
                        for (int i = 0; i < fileArray.size(); i++) {
                            if (fileArray.get(i) == null) {
                                is_addNull = false;
                                break;
                            }
                        }
                        if (is_addNull) {
                            fileArray.add(null);
                        }
                        FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridFileAdapter.notifyDataSetChanged();
                    }
                });
                holder.add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos",(Serializable)single_file_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave",false);
                        bundle.putBoolean("isNet",true);
                        CommonUtils.launchActivity(EditStallPhotoActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }
        class ViewHolder {
            ImageView add;
            ImageView delete;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 1000:
                gvStall.setEnabled(false);
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    new CompressPhotoUtils().CompressPhoto(this, paths, new CompressPhotoUtils.CompressCallBack() {

                        @Override
                        public void success(String pathList) {
                            path = pathList;
                            if (path.equals("")) {
                                ToastUtils.showShort("出现错误，请重新选择试试");
                                return;
                            }
                            path = path.substring(0, path.length() - 1);
                            sendImage(1,path, "1", "0");
                        }
                    });
                }
                break;
            case 1001:

                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");


                    new CompressPhotoUtils().CompressPhoto(this, paths, new CompressPhotoUtils.CompressCallBack() {

                        @Override
                        public void success(String path) {
                            path2 = path;
                            if (path2.equals("")) {
                                ToastUtils.showShort("出现错误，请重新选择试试");
                                return;
                            }
                            path2 = path2.substring(0,path2.length()-1);
                            sendImage(2,path2,"1","1");
                        }
                    });

                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void sendImage(final int uptype,String img,String stallType,String fileType){
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP_UpImg, LrConstant.POST);
            mRequest.add("action", "FileUploadImage");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", stallType);
            mRequest.add("fileType",fileType);
            mRequest.add("img", img);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, UpImgM.class) {
                        @Override
                        public void doWork(UpImgM data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    isUpdate = true;
                                    if (uptype == 1) {
                                        String url = obj.getString("data");
                                        String[] arr = url.split(",");
                                        if (imgArray.size() > 0) {
                                            imgArray.remove(imgArray.size() - 1);
                                        }
                                        for (int i = 0; i < arr.length; i++) {
                                            imgArray.add(arr[i]);
                                        }
                                        for (int i = 0; i < imgArray.size(); i++) {
                                            PhotoModel photoModel = new PhotoModel();
                                            photoModel.setOriginalPath(imgArray.get(i));
                                            photoModel.setChecked(true);

                                            single_img_photos.add(photoModel);
                                        }
                                        if (imgArray.size() < 3) {
                                            imgArray.add(null);
                                        }

                                        gridImgsAdapter.notifyDataSetChanged();
                                        path = "";
                                    } else if (uptype == 2) {
                                        String url = obj.getString("data");
                                        String[] arr = url.split(",");
                                        if (fileArray.size() > 0) {
                                            fileArray.remove(fileArray.size() - 1);
                                        }
                                        for (int i = 0; i < arr.length; i++) {
                                            fileArray.add(arr[i]);
                                        }
                                        for (int i = 0; i < fileArray.size(); i++) {
                                            PhotoModel photoModel = new PhotoModel();
                                            photoModel.setOriginalPath(fileArray.get(i));
                                            photoModel.setChecked(true);
                                            single_file_photos.add(photoModel);
                                        }
                                        if (fileArray.size() < 9) {
                                            fileArray.add(null);
                                        }
                                        gridFileAdapter.notifyDataSetChanged();
                                        path2 = "";
                                    }

                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onBackPressed() {
        exitEdit();
    }
}

